package com.hm.ibsm.auto.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hm.common.annotation.WebClientRequestIntercept;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.ServerResponse;
import com.hm.ibsm.auto.ManageProperties;
import com.hm.ibsm.manage.service.AuthService;
import com.hm.ibsm.util.ControllerResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Aspect
@Component
public class ApiAspectHandler {

	@Autowired
	private ManageProperties manageProperties;

	@Autowired
	private AuthService authService;

	@Autowired
	private WebClientRequestInterceptHandler webClientRequestInterceptHandler;

	@Around("execution(* com.hm.ibsm.api.Api**.*(..)) && @annotation(intercept)")
	public Object process(ProceedingJoinPoint point, WebClientRequestIntercept intercept) throws Throwable {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

		String uri = request.getRequestURI();
		if (manageProperties.getAuthor().getWhiteList().contains(uri)) {
			return point.proceed();
		}

		String tokenId = ControllerResult.currentTokenId(request);
		String secretKey = ControllerResult.currentSecretKey(request);
		try {
			// 客户端请求拦截检查
			webClientRequestInterceptHandler.handler(intercept, tokenId, uri);
			if (!authService.checkUserAuthTokenInfo(tokenId, secretKey)) {
				throw ServiceException.warning(ErrorCode.NO_DATA_ACCESS);
			}
		} catch (Exception e) {
			log.error(ApiAspectHandler.class.getName(), e.getMessage());
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpStatus.BAD_REQUEST.value());
			response.getWriter().println(JSON.toJSONString(new ServerResponse<String>().failure(e.getMessage()), SerializerFeature.WriteMapNullValue));
			return null;
		}

		return point.proceed();
	}

}
